import { Module } from 'vuex'

// 封装本地存储操作
const STORAGE_KEY = 'userInfo'

function getLocalUserInfo(): any {
  try {
    const data = uni.getStorageSync(STORAGE_KEY)
    return data ? JSON.parse(data) : null
  } catch (error) {
    console.warn('读取本地用户信息失败', error)
    return null
  }
}

function saveLocalUserInfo(userInfo: any): void {
  try {
    if (userInfo) {
      uni.setStorageSync(STORAGE_KEY, JSON.stringify(userInfo))
    } else {
      uni.removeStorageSync(STORAGE_KEY)
    }
  } catch (error) {
    console.warn('保存用户信息到本地失败', error)
  }
}

const userModule: Module<{ userInfo: any }, any> = {
  namespaced: true,
  state: () => ({
    userInfo: getLocalUserInfo()
  }),
  mutations: {
    setUserInfo(state, payload: any) {
      state.userInfo = payload
      saveLocalUserInfo(payload)
    }
  },
  actions: {},
  getters: {
    vip(state): boolean {
      console.log('state.userInfo', state.userInfo)
      console.log('state.userInfo', state.userInfo.isVip)
      return state.userInfo?.isVip
    }
  }
}

export default userModule
